﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.SysEntity.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace BLL.Basis
{
   public class WareHouseBLL:PubMethod
    {

        LoginInfo userLogin;
        Commands cmd;
        ReturnResult rsl;
        public WareHouseBLL()
        {
            //当前登录人信息
            userLogin = new LoginInfo();
            //数据交互
            cmd = new Commands();

        }
       /// <summary>
       /// 仓库列表
       /// </summary>
       /// <param name="pageIndex"></param>
       /// <param name="pageSize"></param>
       /// <param name="pageCount"></param>
       /// <param name="condition"></param>
       /// <returns></returns>
        public ReturnResult getWareHouseList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 and baseCode='"+ userLogin.UserInfo().baseCode +"' ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList<DbWareHouse>("fun_WareHouse_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                var tempList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(list));
                if (tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        if (item["status"].ToString().Equals("open"))
                        {
                            item["statusName"] = "启用";
                        }
                        else {
                            item["statusName"] = "停用";
                        }
                        if (item["isSync"].ToString().Equals("Y"))
                        {
                            item["isSyncName"] = "是";
                        }
                        else
                        {
                            item["isSyncName"] = "否";
                        }
                    }
                }
                rsl.Data = tempList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 仓库数据同步
       /// </summary>
       /// <param name="isAuto"></param>
       /// <returns></returns>
        public ReturnResult SyncWareHouse(bool isAuto=false)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            CuDbHelper cuHelper=new CuDbHelper();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion
                string sql = "select code,name,disabled  from AA_Warehouse ";
                var wTable = cuHelper.getData(sql, baseCode);//获取全部T+仓库信息
                sql = "select * from fun_WareHouse_Info ";
                var qTable = cmd.GetDataTable(sql);//获取系统所有仓库数据信息
                foreach(DataRow r in wTable.Rows)
                {
                    oper = new OperateModel();
                    DbWareHouse ware = new DbWareHouse();
                    ware.baseCode = baseCode;
                    ware.houseCode = r["code"].ToString();
                    ware.houseName = r["name"].ToString();
                    ware.isSync = "Y";
                    //判断仓库是否启用（停用日期是否为空）
                    if (string.IsNullOrWhiteSpace(r["disabled"].ToString()) || r["disabled"].ToString() == "0")
                    {
                        ware.status = "open";
                    }
                    else {
                        ware.status = "close";
                    } 
                    ware.isDel = 0;
                    var dr = qTable.Select("houseCode='" + r["code"].ToString() + "'");
                    if (dr.Length > 0)
                    {
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "houseCode,baseCode";
                    }
                    else
                    {
                        #region 添加操作
                        if (isAuto)
                        {
                            ware.createuser = "admin";
                        }
                        else
                        {
                            ware.createuser = userLogin.UserInfo().userCode;
                        }
                        ware.createtime = getNow();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = ware;
                    list.Add(oper);
                }
                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                }
                if (rsl.Result)
                {
                    var rsl_hw = SyncWarehousePosition(true);//货位信息同步
                    rsl.Result = true;
                    if (rsl_hw.Result)
                    {
                        rsl.Message = "数据同步完成";
                        return rsl;
                    }
                    else
                    {
                        rsl.Message = "仓库同步成功，货位同步失败";
                        return rsl;
                    }
                }
                else
                {
                    rsl.Message = "仓库信息同步失败";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 仓库信息
       /// </summary>
       /// <returns></returns>
        public ReturnResult WareHouseInfo()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_WareHouse_Info ");
                sb.Append("where isDel=0 and status='open'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 获取仓库货位信息
       /// </summary>
       /// <param name="wareHouse">仓库编码</param>
       /// <returns></returns>
        public ReturnResult GetWareHousePosition(string wareHouse)
        {
            rsl = new ReturnResult();
            try
            {
                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                if (string.IsNullOrWhiteSpace(wareHouse))
                {
                    rsl.Message = "没有仓库编码"; return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode code,cName+'('+cCode+')' name from fun_CommonData_Info where isdel=0 ");
                sb.Append(" and parentCode='" + wareHouse + "' and specFile='" + userLogin.UserInfo().baseCode + "'");
                sb.Append(" and isdel=0 and status='Y' and cValues='1'");
                var table = cmd.GetDataTable(sb.ToString());

                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
      /// <summary>
      /// 仓库货位数据同步
      /// </summary>
      /// <param name="isAuto"></param>
      /// <returns></returns>
       public ReturnResult SyncWarehousePosition(bool isAuto=false)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            CuDbHelper cuHelper = new CuDbHelper();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion
                string sql = "select cPosCode,cPosName,cWhCode,bPosEnd from Position";
                var wTable = cuHelper.getData(sql, baseCode);//获取全部U8仓库货位信息
                sql = "select id,cCode,cName,parentCode,specFile from fun_CommonData_Info where cType='WP'";
                var qTable = cmd.GetDataTable(sql);//获取系统所有仓库数据信息
                foreach (DataRow r in wTable.Rows)
                {
                    oper = new OperateModel();
                    DbCommonData position = new DbCommonData();
                    position.specFile = baseCode;
                    position.cCode = r["cPosCode"].ToString();
                    position.cName = r["cPosName"].ToString();
                    position.parentCode = r["cWhCode"].ToString();
                    string isChild = "0";
                    if (bool.Parse(r["bPosEnd"].ToString()))
                    {
                        isChild = "1";//是否是末级
                    }
                    position.cValues = isChild;//是否是末级
                    position.cType = "WP";
                    position.status = "Y";
                    position.cMemo = "仓库货位";
                    position.isDel = 0;
                    var dr = qTable.Select("cCode='" + r["cPosCode"].ToString() + "' and specFile='" + baseCode + "'");
                    if (dr.Length > 0)
                    {
                        oper.Types = OperateModel.OperateType.Edit;
                        position.id = int.Parse(dr[0]["id"].ToString());
                        oper.Conditions = "id";
                    }
                    else
                    {
                        #region 添加操作
                        if (isAuto)
                        {
                            position.createuser = "admin";
                        }
                        else
                        {
                            position.createuser = userLogin.UserInfo().userCode;
                        }
                        position.createtime = getNow();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = position;
                    list.Add(oper);
                }
                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 仓库货位信息
       /// </summary>
       /// <param name="wareCode">仓库编码</param>
       /// <returns></returns>
       public ReturnResult WarePositionList(string wareCode)
       {
           rsl = new ReturnResult();
           try
           {
               StringBuilder sb = new StringBuilder();
               sb.Append("select * from fun_CommonData_Info where cType='WP' and isDel='0' and ");
               sb.Append("specFile='" + userLogin.UserInfo().baseCode + "'");
               sb.Append(" and parentCode='"+ wareCode +"' ");

               var table = cmd.GetDataTable(sb.ToString());
               var list = cmd.TableToDictionary(table);
               var tempList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(list));
                if (tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        if (item["status"].ToString().Equals("Y"))
                        {
                            item["statusName"] = "启用";
                        }
                        else
                        {
                            item["statusName"] = "停用";
                        }
                    }
                }
                rsl.Data = tempList;
              // rsl.Data=list;
               rsl.Result = true;
           }
           catch (Exception ex)
           {
               rsl.Message = ex.Message;
           }
           return rsl;
       }


    }
}
